package com.yuwei.image

import android.content.Context
import android.os.Environment
import com.bumptech.glide.Glide
import com.bumptech.glide.GlideBuilder
import com.bumptech.glide.Registry
import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader
import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory
import com.bumptech.glide.load.engine.cache.LruResourceCache
import com.bumptech.glide.load.engine.cache.MemorySizeCalculator
import com.bumptech.glide.load.model.GlideUrl
import com.bumptech.glide.module.AppGlideModule
import okhttp3.Cache
import okhttp3.OkHttpClient
import java.io.File
import java.io.InputStream

@GlideModule
class CustomGlideModule : AppGlideModule(){
    override fun applyOptions(context: Context, builder: GlideBuilder) {
        //修改内存缓存大小Glide默认内存是当前内存的8分之1
        val memorySize = MemorySizeCalculator.Builder(context).build().memoryCacheSize / 6L
        builder.setMemoryCache(LruResourceCache(memorySize))
        //修改磁盘缓存大小 默认磁盘大小为250M
        builder.setDiskCache(InternalCacheDiskCacheFactory(context,"glide_disk_cache",1024*1024*300))
    }
    override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
        //创建builder对象
        val builder = OkHttpClient.Builder()
        //外部sd卡的缓存目录
        val externalDir = Environment.getExternalStorageDirectory()
        val cacheDir = if(externalDir.exists()){
            "${externalDir.absolutePath}/cacheImage"
        }else{
            //内部sd卡的缓存目录
            "${context.externalCacheDir?.absolutePath}/internalCacheImage"
        }
        //创建缓存目录
        var cacheDirFile = File(cacheDir)
        if(cacheDirFile.exists()){
            cacheDirFile = File(cacheDir)
        }
        //计算缓存大小
        var cacheSize = 50*1024*1024L
        externalDir.totalSpace.let {
            cacheSize = it / 8L
        }
        val netWorkCache = Cache(cacheDirFile,cacheSize)
        builder.cache(netWorkCache)
        val okHttpClient = builder.build()
        //替换网络缓存客户端
        registry.replace(GlideUrl::class.java,InputStream::class.java,OkHttpUrlLoader.Factory(okHttpClient))

    }

}